package com.ushine.web.component.redis;

import com.ushine.web.component.contant.RedisConstant;
import com.ushine.web.component.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: yls
 * @Date: 2021/12/24 13:08
 * @Description: redis分布式锁机制
 * @Version 1.0
 */
@Component
public class RedisLockConfig {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 功能描述:
     * 〈加锁〉
     *
     * @param lockName 锁名称
     * @return : boolean
     * @author : yls
     * @date : 2021/12/10 13:57
     * @throws ServiceException 服务端自定义异常
     */
    public RLock getLock(String lockName, Object businessId) throws ServiceException {
        String key = getRedisLockKey(lockName, businessId);
        //获取锁对象
        return redissonClient.getLock(key);
    }

    /**
     * 功能描述:
     * 〈 获取reids锁 〉
     *
     * @param lockName 锁名称
     * @param businessId 业务id
     * @return : java.lang.String
     * @author : yls
     * @date : 2022/3/11 16:49
     * @throws ServiceException 服务端自定义异常
     */
    private String getRedisLockKey(String lockName, Object businessId) throws ServiceException {
        if (StringUtils.isEmpty(lockName)) {
            throw new ServiceException("分布式锁KEY为空");
        }
        if (businessId == null || "".equals(businessId.toString().trim())) {
            throw new ServiceException("业务ID为空");
        }
        //声明key对象
        return RedisConstant.LOCK_TITLE + RedisConstant.LOCK_SEPARATOR + lockName + RedisConstant.LOCK_SEPARATOR + businessId;
    }
}
